<?php

/*
 * 依设定日期跟新门店和公司
 */

$serverFilePath = $_SERVER["SCRIPT_FILENAME"]; ;//realpath(dirname(__FILE__)); //$_SERVER["SCRIPT_FILENAME"];
$doc_dir = strrpos($serverFilePath, '/crontab');
$doc_dir = substr($serverFilePath, 0, $doc_dir + 1);   //project root 
include_once $doc_dir . '/config/lib/Config.php';
include_once $doc_dir . '/plugin/DDExpressClass.php';
include_once $doc_dir . '/plugin/SSExpressClass.php';
include_once $doc_dir . '/plugin/BaiduLBS.php';
include_once $doc_dir . '/plugin/Logging.php';

$log = new Logging();
$log->lfile('updateExpressAccount');

set_time_limit(0);
error_reporting(E_ALL);
header("Content-type:text/html;charset:utf-8");

$config_ini = $doc_dir . 'config/config.ini';

$ini_array = parse_ini_file($config_ini, true);
$db_array = $ini_array['DB'];
$getWebsite = $ini_array['WebSite'];
$con = mysqli_init();

mysqli_real_connect($con, $db_array['host'], $db_array['id'], $db_array['pwd'], $db_array['database'], $db_array['port']);
mysqli_set_charset($con, $db_array['encoding']);

if($getWebsite['debug']){
//    $status = 'limit 2';
    $status = '';
}else{
    $status = "AND status !=3";
}
//$STOREID =  'AND (s.store_id = 100936 OR s.store_id = 100816)';
//$sql = "SELECT s.id,s.store_id,s.storename,s.front_province,s.front_city,s.front_area,s.front_address,s.phone,s.longitude,s.latitude,c.ss_clientId,c.ss_clientSecret,c.ss_shopId,c.dd_source_id,c.dd_app_secret,c.dd_app_key FROM xd_store AS s LEFT JOIN xd_company AS c ON s.company_id = c.code WHERE s.isdeleted = 0  $status  ";
$sql = "SELECT * FROM xd_store where isdeleted = 0  $status AND length(dd_source_id)>0 AND dd_r is null ";         # 20200415 修改该快递开发资料 在对应店铺下

$result = mysqli_query($con, $sql);
$results = [];
if($result){
    while ($row = @mysqli_fetch_array($result, MYSQLI_ASSOC)) {
        $results[] = $row;
    }
}

# 执行前 请先确定 后台分司 已配置快递开发者账号信息
# 执行前 请先确定 后台确认已配置了 门店的电话 且 必须为11位手机号


# DD    business = 业务类型(食品小吃-1,饮料-2,鲜花-3,文印票务-8,便利店-9,水果生鲜-13,同城电商-19, 医药-20,蛋糕-21,酒品-24,小商品市场-25,服装-26,汽修零配-27,数码-28,小龙虾-29, 其他-5) 2019-11-20 定 21
# DD 可一次添加多个店铺，这里配合闪送 一对一推送添加
# DD 添加相同店铺  提示false 不做任何动作


# SS goodType = 发件类型，1:餐饮;2:文件;3:蛋糕;4:鲜花;5:零食;6:其他;7:生鲜；8:数码；9:商超） 2019-11-20 定 3
# SS 一次只能添加一个店铺
# SS 添加相同店铺 会视为更新此店铺


################################## 20191212 确认 闪送 API 添加店铺下线维护 周期不明！ 需要透过闪送技术手动添加
if($results && count((array)$results) > 0){
    $dt = date('Y-m-d H:i:s');
    foreach ($results as $k => $val) {
        $id = $val['id'];
        if(!$val['phone']){
            $log->lwrite($dt.',pushError：'.$val['store_id'].' ----- 无门店联系方式');
            continue;
        }

        /*
        # 20191212 确认 闪送 API 添加店铺下线维护 周期不明！
        # 闪送
        if($val['ss_clientId'] && $val['ss_clientSecret'] && $val['ss_shopId']){
            $parameters = [];
            $sse = new SSExpressClass($getWebsite['debug'],$val['ss_clientId'],$val['ss_clientSecret'],$val['ss_shopId']);
            $parameters['thirdStoreId'] = $val['store_id'];                            # 第三方门店id
            $parameters['storeName'] = $val['storename'];                              # 门店名称
            $parameters['cityName'] = $val['front_city'];                              # 城市名称
            $parameters['phone'] = $val['phone'];                                      # 联系人手机号
            $parameters['address'] = $val['front_address'];                            # 门店地址
            $parameters['addressDetail'] = $val['front_address'];                      # 门店详细地址(楼/单元/楼层)
            $parameters['goodType'] = 3;                                               # 店铺发件类型
            $parameters['latitude'] = $val['latitude'];                                # 门店纬度
            $parameters['longitude'] = $val['longitude'];                              # 门店经度
            $info_jj ['ss_result']= $sse->add_shop($parameters);
            $info_jj['date'] = $dt;
            $ss = json_encode($info_jj, JSON_UNESCAPED_UNICODE);
            $sql_s = "update xd_store set ss_r = '$ss' WHERE id =  $id";
            $result = mysqli_query($con, $sql_s);
            $log->lwrite($dt.',SSpushInfo：'.json_encode($parameters, JSON_UNESCAPED_UNICODE));
            $log->lwrite($dt.',SSResultInfo：'.$ss);
        }else{
            $log->lwrite($dt.',SSpushError-缺少参数：'.json_encode($val, JSON_UNESCAPED_UNICODE));
        }
        */
        # 达达
        if($val['dd_source_id'] && $val['dd_app_secret'] && $val['dd_app_key']){
            $parameters = [];
            $dde = new DDExpressClass($getWebsite['debug'],$val['dd_source_id'],$val['dd_app_key'],$val['dd_app_secret']);
            $parameters = [0=>[
                'station_name' => $val['storename'],
                'business' => 21,
//                'city_name' => str_replace('市','',$val['front_city']),
//                'area_name' => str_replace('区','',$val['front_area']),
                'city_name' => $val['front_city'],
                'area_name' => $val['front_area'],
                'station_address' => $val['front_address'],
                'lng' => $val['longitude'],
                'lat' => $val['latitude'],
                'contact_name' => $val['storename'],
                'phone' => $val['phone'],
                'origin_shop_id'=>$val['store_id'],
//           'id_card'=>'',     # 联系人身份证
//           'username'=>'',    # 达达商家app账号 2019-11-20 讨论不要
//           'password'=>'',    # 达达商家app账号
            ]];
            $info ['dd_result']= $dde->addShop($parameters);
            $info['date'] = $dt;
            $dd = json_encode($info, JSON_UNESCAPED_UNICODE);
            $sql_d = "update xd_store set dd_r = '$dd' WHERE id =  $id";
            $result = mysqli_query($con, $sql_d);
            $log->lwrite($dt.', dd_source_id:'.$val['dd_source_id'].',DDpushInfo：'.json_encode($parameters, JSON_UNESCAPED_UNICODE));
            $log->lwrite($dt.',DDResultInfo：'.json_encode($info, JSON_UNESCAPED_UNICODE));
        }else{
            $log->lwrite($dt.',DDpushError-缺少参数：'.json_encode($val, JSON_UNESCAPED_UNICODE));
        }

    }
}

echo '---------------------------------------------------';
//echo '<pre>';
//print_r($results);